import React, { useRef, useState, useEffect } from 'react';
import useMessage from '../../usewebsocket';
function Messages() {
  const { message, sendMessage } = useMessage('ws://localhost:23456');
  const [list, setList] = useState<Array<string>>([]);
  useEffect(() => {
    list.push(message)
    setList([...list])
  }, [message])
  const inputRef = useRef<HTMLInputElement>(null);
  const send = () => {
    const msg = inputRef.current!.value;
    list.push(JSON.stringify({
      content: msg
    }))
    setList([...list]);
    sendMessage(JSON.stringify({
      content: msg
    }));
    inputRef.current!.value = '';
  }
  return (
    <div>
      <div className='chat'>
        {
          list.map((item, index) => {
            return <div key={index}>{item && JSON.parse(item).content}  </div>
          })
        }
      </div>
      <div>
        <input ref={inputRef} type='text' />
        <button onClick={send}>发送</button>
      </div>
    </div>
  );
}
export default Messages;